#include "DataBaseManager.h"
#include "Common.h"
#include "Widget_Start.h"
#include "Widget_Reader_TextBox.h"

#include <QtSql/QSqlQuery>
#include <QtSql/QSqlRecord>
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QSplitter>
#include <QtGui/QTextDocument>
#include <QtWebKit/QWebView>

namespace Jonathan
{

   Widget_Start::Widget_Start(QWidget *parent) :
       QWidget(parent)
   {
      Widget_Reader_TextBox* dailyDevotional = new Widget_Reader_TextBox ();

      QSplitter* splitter = new QSplitter (Qt::Horizontal);
      splitter->addWidget (this->CreateRandomPanel (splitter));
      splitter->addWidget (dailyDevotional);

      QGridLayout* layout = new QGridLayout (this);
      layout->setMargin (0);
      layout->setSpacing (0);
      layout->addWidget (splitter);
      this->setLayout (layout);
   }

   QWidget* Widget_Start::CreateRandomPanel (QWidget* parent)
   {
      Widget_Reader_TextBox* randomVerse = new Widget_Reader_TextBox (parent);

      QString randomHtml = Common::TableStart ();
      QList<TreeItem_Book*> books = DataBaseManager::GetInstance ()->GetBooks ();
      foreach (TreeItem_Book* book, books)
      {
         QSqlQuery query = book->GetDatabase ().exec ("SELECT * FROM book_text ORDER BY RANDOM() LIMIT 1;");
         if (query.next ())
         {
            randomHtml.append ("<tr>");
            randomHtml.append (Common::BoldCell (Common::ALIGN_LEFT, 2));
            randomHtml.append (book->GetName ());
            randomHtml.append ("</td>");
            randomHtml.append ("</tr>");

            randomHtml.append ("<tr>");
            randomHtml.append (Common::VerseCell (Common::ALIGN_LEFT));
            QSqlRecord record = query.record ();
            if (book->HasSubBooks ())
            {
               randomHtml.append (record.value (Common::BOOK).toString ());
               randomHtml.append (" ");
            }
            randomHtml.append (record.value (Common::CHAPTER).toString ());
            randomHtml.append (":");
            randomHtml.append (record.value (Common::VERSE).toString ());
            randomHtml.append ("</td>");
            randomHtml.append ("<td>");
            randomHtml.append (record.value (Common::TEXT).toString ());
            randomHtml.append ("</td>");
            randomHtml.append ("</tr>");
         }
      }
      randomHtml.append (Common::TableEnd ());
      randomVerse->setHtml (randomHtml);

      return randomVerse;
   }

}
